import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import storage from '../../shared/storage';
import { HomeService } from "../home.service";
import mqttTool from '../../shared/mqtt/mqttTool';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { TranslateService } from '@ngx-translate/core';
import { Router, ActivatedRoute, NavigationEnd, ParamMap } from '@angular/router';
import SysData from '../../shared/sysData';
import Mysocket from '../../shared/mySocket';
@Component({
  selector: 'app-device-debug-cab07',
  templateUrl: './device-debug-cab07.component.html',
  styleUrls: ['./device-debug-cab07.component.scss']
})
export class DeviceDebugCab07Component implements OnInit {
  @Output() close: EventEmitter<boolean> = new EventEmitter<boolean>();
  @Output() offLine: EventEmitter<boolean> = new EventEmitter<boolean>();
  isSpinning: boolean = false;
  currentOptions = {};//当前所有参数
  isLampShow: boolean = false;//信号灯是否显示
  lampCount = 0;//亮灯个数（灯从下往上对应1-8）
  alarmTimesTitle = '';//报警次数Title
  resetTitle = '';//恢复出厂设置Title
  getParamTitle = '';//读取参数Title
  alarmCircleColor = 'lightGray';
  formatOne = percent => "";
  //moduleCode
  optionCmdList: any = storage.getSessionStorage("AA10_CAB07_OPTION_CMD");//天线参数配置
  otherCmdList: any = storage.getSessionStorage("AA10_CAB07_OTHER_CMD");//其他参数
  //选择项
  modulationFreqList: any = storage.getSessionStorage("AA10_CAB07_MODULATION_FREQ");//调频
  centerFreqList: any = storage.getSessionStorage("AA10_CAB07_CENTER_FREQ");//中心频率
  bandWidthList: any = storage.getSessionStorage("AA10_CAB07_BAND_WIDTH"); //带宽
  antiNoiseList: any = storage.getSessionStorage("AA10_CAB07_ANTI_NOISE");//抗干扰
  rxSoundList: any = storage.getSessionStorage("AA10_CAB07_RX_SOUND");//声音样式
  rxVolumeList: any = storage.getSessionStorage("AA10_CAB07_RX_VOLUME");//音量
  preAlertList: any = storage.getSessionStorage("AA10_CAB07_PRE_ALERT"); //预警开关
  txSoundList: any = storage.getSessionStorage("AA10_CAB07_TX_SOUND");//发射板声音
  txVolumeList: any = storage.getSessionStorage("AA10_CAB07_TX_VOLUME");//发射板音量
  LoginForm: any = storage.getSessionStorage('LoginForm');
  displayHitCount: number;
  constructor(
    private router: Router,
    private homeService: HomeService,
    private message: NzMessageService,
    private modalService: NzModalService,
    private translateService: TranslateService) { }

  ngOnInit() {
    this.alarmTimesTitle = this.getTitleByValue(this.otherCmdList, '0a');
    this.resetTitle = this.getTitleByValue(this.otherCmdList, '10');
    this.getParamTitle = this.getTitleByValue(this.otherCmdList, '7f');
    Mysocket.oncloseWS();
    setTimeout(() => {
      this.initSocketMsg();
      Mysocket.createSocket();
      setTimeout(()=>{
        this.readParams();
      }, 500);
    }, 500);
  }

  exit() {
    this.close.emit(true);
  }

  ngOnDestroy(): void {
    Mysocket.oncloseWS();
  }

  initSocketMsg() {
    //接收信息
    let _this = this;
    window.addEventListener("onmessageWS", function (e) {
      let data = (JSON.parse(e['detail']['data']['data']));
      console.log(data);
      switch (data.moduleCode) {
        case '85':
          //报警灯
          _this.alarm();
          _this.readParams();
          break;
        case '81':
          //信号灯
          var lampList = JSON.parse(data.val);
          var count = 0;
          lampList.forEach((element, index) => {
            if (element > 50) {
              count = index + 1;
            }
          });
          _this.lampCount = count;
          break;
        case '10':
          //恢复出厂设置
          _this.readParams();
          break;
        default:
          _this.currentOptions[data.moduleCode] = data.val;
          break;
      }
    });
  }

  //读取参数
  readParams() {
    this.sendOrder(2, '7f', '');
  }

  //报警
  alarm() {
    var times = 0;
    var time = setInterval(() => {
      if (times >= 6) {
        clearInterval(time);
      } else {
        this.alarmCircleColor = this.alarmCircleColor === 'red' ? 'lightGray' : 'red';
        times++;
      }
    }, 500);
  }

  //信号灯操作
  lampShowChange() {
    if (this.isLampShow) {
      //开启信号灯
      this.lampCount = 0;
      this.sendOrder(3, '81', '');
    } else {
      //关闭信号灯
      this.lampCount = 0;
      this.sendOrder(3, '82', '');
    }
  }

  //下发命令
  sendOrder(type, code, val) {
    let data = {
      LoginForm: this.LoginForm,
      DeviceMessage: {
        moduleCode: code,
        val: val,
        moduleType: type
      }
    };
    this.homeService.order(data).subscribe(res => {
      if (res.status == 1) {
        this.message.success(this.translateService.instant('eas_order_success'));
      } else {
        this.message.error(res.message);
      }
    });
  }

  //根据modileCode获取title
  getTitleByValue(list, value) {
    let title = '';
    list.forEach(element => {
      if (element.value === value) {
        title = element.title;
      }
    })
    return title;
  }
}
